package com.hiof.servercommunication.push;

import android.util.Log;
import com.hiof.servercommunication.push.beans.SendPacket;
import com.hiof.utility.Utility;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by IntelliJ IDEA.
 * User: manish
 * Date: 3/26/12
 * Time: 9:37 AM
 * To change this template use File | Settings | File Templates.
 */
public class JobQueueRequestProcessor implements Runnable {

    private static boolean isAlive = false;
    private static LinkedBlockingQueue<SendPacket> jobQueue = new LinkedBlockingQueue<SendPacket>();
    private static JobQueueRequestProcessor instance;

    public static JobQueueRequestProcessor getInstance() {
        if (null == instance) {
            instance = new JobQueueRequestProcessor();
            isAlive = true;
        }
        return instance;
    }

    public void startThread() {
        if (!isAlive) {
            isAlive = true;
        }
    }

    public void stopThread() {
        isAlive = false;
        jobQueue.clear();
    }

    @Override
//    @SuppressWarnings("SleepWhileInLoop")
    public void run() {
        while (isAlive) {
            if (jobQueue.size() > 0) {
                Log.i("Job Queue", "job size: " + jobQueue.size());
                SendPacket packet = jobQueue.peek();
                if (packet != null) {
                    processJob(packet);
                }
            } else {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Utility.error(this.getClass().toString(), e.getMessage());
                }
            }
        }

    }

    private void processJob(SendPacket packet) {
        Sender sender = SenderFactory.getSenderObject(packet);
        try {
            boolean result = sender.send();
            if (result == true) {
                removeJobFromQueue();
            }
        } catch (Exception e) {
            Log.e("Error", "Error:" + e.getMessage());
        }
    }

    public void addJobToQueue(SendPacket packet) {
        jobQueue.add(packet);
    }

    public void removeJobFromQueue() {
        try {
            jobQueue.take();
        } catch (InterruptedException e) {
            Utility.error(this.getClass().toString(), e.getMessage());
        }
    }

    public void removeAllJobs() {
        jobQueue.clear();
    }
}